#include <iostream>
using namespace std;
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

/* 全局变量 */
int g_ticket = 10;

/* 线程函数 */
/* 线程共享全局变量 */
void * thread_func1(void * arg)
{
    /* 设置线程分离 */
    pthread_detach(pthread_self());
    int val1 = *(int *)arg;

    int cnt = 30;
    while(g_ticket > 0)
    {
        usleep(1500);
        g_ticket--;
        printf("I am new thread1 %ld! , g_ticket = %d\n",pthread_self(),g_ticket);
    }
    /* 线程退出 */
    pthread_exit(NULL);
}

void * thread_func2(void * arg)
{
        /* 设置线程分离 */
    pthread_detach(pthread_self());
    int val2 = *(int *)arg;

    int cnt = 30;
    while(g_ticket > 0)
    {
        sleep(1);
        g_ticket--;
        printf("I am new thread2 %ld! , g_ticket = %d\n",pthread_self(),g_ticket);
        
    }
    /* 线程退出 */
    pthread_exit(NULL);
}

void * thread_func3(void * arg)
{
        /* 设置线程分离 */
    pthread_detach(pthread_self());
    int val3 = *(int *)arg;

    int cnt = 30;
    while(g_ticket > 0)
    {
        usleep(1200);
        g_ticket--;
        printf("I am new thread3 %ld! , g_ticket = %d\n",pthread_self(),g_ticket);
        
    }
    /* 线程退出 */
    pthread_exit(NULL);
}


int main()
{
#if 0
    pid_t pid = getpid();
    pthread_t tid = pthread_self();

    cout << "pid:" << pid << endl;
    cout << "tid" << tid <<endl;
#endif
    /* 创建线程 */
    pthread_t tid1;
    int val1 = 100;
    int ret = pthread_create(&tid1,NULL,thread_func1,(void *)&val1);
    if(ret != 0)
    {
        perror("pthread_create error");
        exit(1);
    }

    pthread_t tid2;
    int val2 = 200;
    ret = pthread_create(&tid2,NULL,thread_func2,(void *)&val2);
    if(ret != 0)
    {
        perror("pthread_create error");
        exit(1);
    }

    pthread_t tid3;
    int val3 = 2030;
    ret = pthread_create(&tid3,NULL,thread_func3,(void *)&val3);
    if(ret != 0)
    {
        perror("pthread_create error");
        exit(1);
    }

    int cnt = 50;
    while(cnt--)
    {
        printf("I am main thread!\n");
        sleep(1);
    }

    /* 阻塞回收线程资源 */
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}